package org.example.leetCode;

import java.util.HashMap;

/**
 * 560. 和为 K 的子数组
 * 给你一个整数数组 nums 和一个整数 k ，请你统计并返回 该数组中和为 k 的子数组的个数 。
 * 子数组是数组中元素的连续非空序列。
 */
public class Code560 {
    public int subarraySum(int[] nums, int k) {
        int size = nums.length;
        int result = 0;
        int sum = 0;
        int right = 0;
        for (int left = 0; left < size; left++) {
            if (nums[left] == k) {
                result++;
            }
            sum = nums[left];
            right = left + 1;
            while (right<size){
                sum += nums[right++];
                if(sum==k){
                    result++;
                }
            }
        }
        return result;
    }
    public int subarraySum1(int[] nums, int k) {
        int count=0,pre=0;
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0,1);
        for(int i=0;i<nums.length;i++){
            pre+=nums[i];
            if(map.containsKey(pre-k)){
                count+=map.get(pre-k);
            }
            map.put(pre,map.getOrDefault(pre,0)+1);
        }
        return count;
    }

    public static void main(String[] args) {
        Code560 solution = new Code560();

        int[] nums1 = {1, 1, 1};
        int k1 = 2;
        System.out.println("Test case 1: " + solution.subarraySum1(nums1, k1)); // Expected output: 2

        int[] nums2 = {1, 2, 3};
        int k2 = 3;
        System.out.println("Test case 2: " + solution.subarraySum1(nums2, k2)); // Expected output: 2

        int[] nums3 = {3, 4, 7, 2, -3, 1, 4, 2};
        int k3 = 7;
        System.out.println("Test case 3: " + solution.subarraySum1(nums3, k3)); // Expected output: 4
    }
}
